from lib.web.rs import Resource
from lib.db.mgr import DBMgr
from lib.util.crypto import JWT
from lib.util.tools import FS

class UserService(Resource):
    __slots__ = ()

    def regist(self, **kwargs):
        if isinstance(kwargs, dict) and 'un' in kwargs and 'u_type' in kwargs:
            with DBMgr.getConnect() as conn:
                try:
                    cursor = conn.cursor()
                    
                    un = kwargs['un']
                    u_type = kwargs['u_type']
                    cursor.execute('select count(1) as total from t_user where un="%s"' % (un))
                    res = cursor.fetchone()
                    if res[0] > 0: return self.response(self.httpStatus.INTERNAL_SERVER_ERROR, '用户名已存在！')

                    cursor.execute('insert into t_user(un, u_type, pwd) values("%s",%s,"%s")' % (un, u_type, kwargs.get('pwd', '')))
                    uid = cursor.lastrowid

                    cursor.execute('insert into t_user_info(uid,name,cp_number,credit_code,level,group_type) values(%s,"%s","%s","%s",%s,%s)' % (uid, kwargs.get('name', un), kwargs.get('cp_number', ''), kwargs.get('credit_code', ''), kwargs.get('level', -1), kwargs.get('group_type', -1)))

                    conn.commit()

                    return self.response()
                except Exception as e:
                    self.log.get().error('[line: %s]err: %s' % (e.__traceback__.tb_lineno, e))
                    conn.rollback()
                    return self.response(self.httpStatus.INTERNAL_SERVER_ERROR, e)
                finally:
                    if cursor: cursor.close()
        return self.response(self.httpStatus.BAD_REQUEST)
    def login(self, **kwargs):
        if isinstance(kwargs, dict) and 'un' in kwargs:
            ok, total, res = self.accessor.select('t_user', 'id,un,u_type,is_active', {'un': kwargs['un'], 'pwd': kwargs.get('pwd', '')})
            if ok:
                if total > 0:
                    data = res[0]
                    if data['is_active'] == 0: return self.response(self.httpStatus.FORBIDDEN, '账号已被禁用！')
                    data.pop('is_active')
                    token = JWT.generate(**data)
                    return self.response(data={'data': data, 'token': token})
                else:
                    return self.response(self.httpStatus.UNAUTHORIZED, '登陆失败！')
            self.log.get().error('err: %s' % res)
            return self.response(self.httpStatus.INTERNAL_SERVER_ERROR, res)

        return self.response(self.httpStatus.BAD_REQUEST)
    def set_logo(self, kwargs, files):
        if isinstance(kwargs, dict) and 'user_id' in kwargs and 'files' in files:
            fns = FS.upload(files.getlist('files'), self.config['source_path'])
            print(fns)
            return self.response(data=fns)
        
        return self.response(self.httpStatus.BAD_REQUEST)
    def get_logo(self, **kwargs):
        if isinstance(kwargs, dict) and 'file_name' in kwargs:
            return  FS.download(self.config['source_path'] + kwargs['file_name'])
        
        return self.response(self.httpStatus.BAD_REQUEST)
    
    def test(self, **kwargs):
        pass